package com.tnovoselec.server.news.worker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.tnovoselec.server.news.beans.IItem;
import com.tnovoselec.server.news.util.XMLUtil;

public class RSSParser {

	private String channelName;
	private List<IItem> items;
	private IItem activeItem;

	private String url;

	public RSSParser(String url, IItem activeItem) {
		this.url = url;
		this.activeItem = activeItem;
		this.items = new ArrayList<IItem>();
	}

	public String getChannelName() {
		return channelName;
	}

	public void setChannelName(String channelName) {
		this.channelName = channelName;
	}

	public List<IItem> getItems() {
		return items;
	}

	public void setItems(List<IItem> items) {
		this.items = items;
	}

	public void parse() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			//httpclient.getParams().setParameter("Accept-Encoding", "UTF-8");
			HttpGet httpget = new HttpGet(this.url);
			
		//	ResponseHandler<String> responseHandler = new BasicResponseHandler();
			
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
			    public String handleResponse(final HttpResponse response)
			        throws HttpResponseException, IOException {
			        StatusLine statusLine = response.getStatusLine();
			        if (statusLine.getStatusCode() >= 300) {
			            throw new HttpResponseException(statusLine.getStatusCode(),
			                    statusLine.getReasonPhrase());
			        }

			        HttpEntity entity = response.getEntity();
			        return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
			    }
			};
			
			String responseBody = httpclient.execute(httpget, responseHandler);

			byte[] data = responseBody.getBytes("UTF-8");
			String temp = new String(data, "UTF-8");
			Document doc = XMLUtil.getDoc(repairBugString(temp).getBytes("UTF-8"));
			Element root = doc.getDocumentElement();

			NodeList nodes = root.getElementsByTagName(activeItem.getItemTagName());
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				IItem item = (IItem) activeItem.clone();
				item.resetImages();
				NodeList childs = node.getChildNodes();
				for (int j = 0; j < childs.getLength(); j++) {
					Node child = childs.item(j);
					if (child.getNodeName().equals(activeItem.getTitleTagName())) {
						item.setTitle(child.getTextContent());
					} else if (child.getNodeName().equals(activeItem.getDescriptionTagName())) {
						item.setDescription(child.getTextContent());
					} else if (child.getNodeName().equals(activeItem.getPubDateTagName())) {
						item.setPubDate(child.getTextContent());
					} else if (child.getNodeName().equals(activeItem.getLinkTagName()) || child.getNodeName().equals(activeItem.getImagesTagName())) {
						handleLink(child, item, activeItem);
					}
				}
				items.add(item);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void handleLink(Node child, IItem currentItem, IItem activeItem) {
		if (child.hasAttributes()) {
			List<String> atts = XMLUtil.getNodeAttributes(child);
			String url = null;
			String type = null;

			for (String att : atts) {
				if (att.equals("href")) {
					url = XMLUtil.getNodeAttribute(child, att);
				} else if (att.equals("type")) {
					type = XMLUtil.getNodeAttribute(child, att);
				}

			}
			if (url != null && type == null) {
				currentItem.setLink(url);
			} else if (url != null && type.contains("image")) {
				currentItem.getImages().add(url);
			}
		} else if(child.getNodeName().equals("thumbnail")){
			currentItem.getImages().add(child.getTextContent());
		}else {
			currentItem.setLink(child.getTextContent());
		}
	}

	private String repairBugString(String orig) {

		return orig.substring(orig.indexOf("<?"));
	}

}
